package com.cn.netty;

import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

@Slf4j
public class PromiseDemo {

    public static void main(String[] args) {
        DefaultEventLoopGroup eventExecutors = new DefaultEventLoopGroup();
        EventLoop next = eventExecutors.next();
        Promise<String> objectPromise = next.newPromise();
        GenericFutureListener<Future<? super String>> listener = new GenericFutureListener<Future<? super String>>() {
            @Override
            public void operationComplete(Future future) throws Exception {
                log.info("阻塞");
                Object o = future.get();
                log.info("o -> {}", o);
            }
        };
        objectPromise.addListeners(listener);

        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //通过setSuccess 把 Listeners丢到 EventLoop 工作线程中去执行
        objectPromise.setSuccess("helloworld");
        boolean trySuccess_helloworld = objectPromise.trySuccess("trySuccess helloworld");
        //如果已经设置了success。那么trySuccess 设置失败
        log.info("trySuccess_helloworld -> {}", trySuccess_helloworld);
        log.info("done");
    }


    @Test
    public void test(){
        EventLoopGroup eventExecutors = new NioEventLoopGroup(22);
        EventLoop next = eventExecutors.next();
        Promise<Object> objectPromise = next.newPromise();

        objectPromise.addListeners(new GenericFutureListener<Future<? super Object>>() {
            @Override
            public void operationComplete(Future<? super Object> future) throws Exception {
                log.info("addListeners finish...");
            }
        });

        log.info("trySuccess");
        boolean b = objectPromise.trySuccess(null);
        log.info("end");


        objectPromise.addListeners(new GenericFutureListener<Future<? super Object>>() {
            @Override
            public void operationComplete(Future<? super Object> future) throws Exception {
                log.info("addListeners finish...");
            }
        });

    }


}
